﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ChMetody_3
{
    class Heuristic
    {
    public static List<double> Solve(string func, double a, double b, double eps)
        {
            int maxk = 150;
            int maxn = 30;
            int kolkor = 0;
            int kolt = 0;
            int n = 0;
            double x = 9999;
            bool log = true;
            bool temp = false;   
            List<double> korn = new List<double>();
            while (log || temp)
            {
                if (temp==false)
                {
                    x = Ini(a, b, ref n, ref kolt);
                    log = false;
                }
                if (kolt > maxk)
                {
                    return korn;
                }
                else
                {
                    double y = Functions.f(func, x);
                    if (Math.Abs(y) > eps)
                    {
                        n = n + 1;
                        double M = Diff(func, x);
                        if (Math.Abs(M) < eps)
                        {
                            log = true;
                            temp = false;
                        }
                        else
                        {
                            temp = true;
                            x = x - y / M;
                            if ((x < a) || (x > b) || (n > maxn))
                            {
                                log = true;
                                temp = false;
                            }
                        }
                    }
                    else
                    {
                        temp = false;
                        New_korn(ref korn, x, y, ref kolkor);
                        log = true;
                    }
                }              
            }
            return korn;
        }

        public static double Ini(double a, double b, ref int n, ref int kolt)
        {
            n = 0;
            kolt += 1;
            Random r = new Random();
            return a + (b - a) * r.NextDouble();
        }

        public static double Diff(string func, double x)
        {
            double h = Math.Pow(10, -5);
            return (Functions.f(func, x + h) - Functions.f(func, x - h)) / (2 * h);
        }


        public static void New_korn(ref List<double> korn, double x, double y, ref int kolkor)
        {
            double eps = Math.Pow(10, -6);
            bool temp = true;
            for (int i = 0; i < kolkor; i++)
            {
                double V = Math.Abs(korn[i] - x);
                if (V < eps)              
                    return ;
            }
                kolkor = kolkor + 1;
                korn.Add(x);
        }
    }
}
